<template>
  <div class="app-container">
    <!--form 组件-->
    <eForm ref="form" :is-add="isAdd" :dicts="dicts" :dictmap="dictMap"/>
    <el-row :gutter="20" >
      <!--部门数据-->
      <!-- <el-col :xs="7" :sm="6" :md="4" :lg="4" :xl="4">
        <div class="head-container">
          <el-input v-model="deptName" clearable placeholder="输入部门名称搜索" prefix-icon="el-icon-search" style="width: 100%;" class="filter-item" @input="getDeptDatas"/>
        </div>
        <el-tree :data="depts" :props="defaultProps" :expand-on-click-node="false" default-expand-all @node-click="handleNodeClick"/>
      </el-col> -->
      <!--用户数据-->
   
        <!--工具栏-->
        <div class="head-container">
          <!-- 搜索 -->
          <!-- <el-input v-model="query.value" clearable placeholder="输入关键字搜索" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery"/>
          <el-select v-model="query.type" clearable placeholder="类型" class="filter-item" style="width: 130px">
            <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select> -->


          <!-- <el-select v-model="query.enabled" clearable placeholder="状态" class="filter-item" style="width: 90px" @change="toQuery">
            <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select>
          <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button> -->
          <!-- 新增 -->
          <div v-permission="['ADMIN','USER_ALL','USER_CREATE']" style="display: inline-block;margin: 0px 2px;">
            <el-button
              class="filter-item"
              size="mini"
              type="primary"
              icon="el-icon-plus"
              @click="addRule">新增</el-button>
			   <el-button
              class="filter-item"
              size="mini"
              type="success"
              icon="el-icon-edit-outline"
              @click="editDetails(editData)">详情</el-button>
			   <el-button
              class="filter-item"
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delet(editData)">删除</el-button>
          </div>
          <!-- 导出 -->
          <!-- <div style="display: inline-block;">
            <el-button
              v-permission="['ADMIN']"
              :loading="downloadLoading"
              size="mini"
              class="filter-item"
              type="warning"
              icon="el-icon-download"
              @click="download">导出</el-button>
          </div> -->
        </div>
        <!--表格渲染-->
        <el-table v-loading="loading" :data="data" size="small" style="width: 100%;" @selection-change="handleSelectionChange">
		  <el-table-column type="selection" width="50"></el-table-column>	
          <el-table-column label="检查类型" align="center">
            <template slot-scope="scope">
              <div v-for="item in dictMap.loancheck_type" :key="item.id">
                <span v-if="scope.row.checkType.toString() === item.value">{{ item.label }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="检查对象" align="center">
            <template slot-scope="scope">
              <div v-for="item in dictMap.loancheck_obj" :key="item.id">
                <span v-if="scope.row.checkObj.toString() === item.value">{{ item.label }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="检查方式" align="center">
            <template slot-scope="scope">
              <div v-for="item in dictMap.loancheck_mode" :key="item.id">
                <span v-if="scope.row.checkMode.toString() === item.value">{{ item.label }}</span>
              </div>
            </template>
          </el-table-column>
		  <el-table-column label="任务生成规则" align="center">
            <template slot-scope="scope">
              <div v-for="item in dictMap.loancheck_rule" :key="item.id">
                <span v-if="scope.row.rue.toString() === item.value">{{ item.label }}</span>
              </div>
            </template>
          </el-table-column>
		   <el-table-column label="检查频率" align="center">
            <template slot-scope="scope">
              <div v-for="item in dictMap.loancheck_frequency" :key="item.id">
                <span v-if="scope.row.checkFrequency.toString() === item.value">{{ item.label }}</span>
              </div>
            </template>
          </el-table-column>
		  <el-table-column label="执行结构" align="center" prop="createDept">
            <template slot-scope="scope">
			   <span v-if="scope.row.operator!=null">{{scope.row.operator.name}}</span>
            </template>
          </el-table-column>
		  <el-table-column label="执行期限" align="center">
            <template slot-scope="scope">
              <div v-for="item in dictMap.loancheck_term" :key="item.id">
                <span v-if="scope.row.operatorPeriod.toString() === item.value">{{ item.label }}</span>
              </div>
            </template>
          </el-table-column>
		  <el-table-column label="未完成措施" :show-overflow-tooltip="true" align="center">
            <template slot-scope="scope">
              <div v-for="item in dictMap.loancheck_measure" :key="item.id">
                <span v-if="scope.row.measure.toString() === item.value">{{ item.label}}</span>
              </div>
            </template>
          </el-table-column>
       


		  
		  <!-- <el-table-column prop="realName" label="用户名"/>
          <el-table-column prop="phone" label="电话"/>
          <el-table-column :show-overflow-tooltip="true" prop="email" label="邮箱"/>
          <el-table-column label="部门 / 岗位">
            <template slot-scope="scope">
              <div>{{ scope.row.dept.name }} / {{ scope.row.job.name }}</div>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <div v-for="item in dicts" :key="item.id">
                <el-tag v-if="scope.row.enabled.toString() === item.value" :type="scope.row.enabled ? '' : 'info'">{{ item.label }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建日期">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="checkPermission(['ADMIN','USER_ALL','USER_EDIT','USER_DELETE'])" label="操作" width="125" align="center">
            <template slot-scope="scope">
              <el-button v-permission="['ADMIN','USER_ALL','USER_EDIT']" size="mini" type="primary" icon="el-icon-edit" @click="edit(scope.row)"/>
              <el-popover
                v-permission="['ADMIN','USER_ALL','USER_DELETE']"
                :ref="scope.row.id"
                placement="top"
                width="180">
                <p>确定删除本条数据吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                  <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
                </div>
                <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini"/>
              </el-popover>
            </template>
          </el-table-column> -->
        </el-table>
        <!--分页组件-->
        <el-pagination
          :total="total"
          :current-page="page + 1"
          style="margin-top: 8px;"
          layout="total, prev, pager, next, sizes"
          @size-change="sizeChange"
          @current-change="pageChange"/>
  
    </el-row>

      <el-dialog :visible.sync="dialogAdd" title="新增用户" append-to-body width="1200px">
            <el-form ref="formAdd"    size="small" label-width="150px">
                      	   <el-form-item label="检查对象"  style="display:inline-block;width:48%;" :required='must'>
								<el-select v-model="formAdd.checkObj"  placeholder="请先选择检查对象" style="width: 370px;">
										<el-option
											v-for="item in dictMap.loancheck_obj"
											:key="item.id"
											:label="item.label"
											:value="item.value"/>
								</el-select>
							</el-form-item>
							<el-form-item label="检查类型"  style="display:inline-block;width:48%;" :required='must'>
								<el-select v-model="formAdd.checkType"  placeholder="请先选择检查类型" style="width: 370px;">
										<el-option
											v-for="item in dictMap.loancheck_type"
											:key="item.id"
											:label="item.label"
											:value="item.value"/>
								</el-select>
							</el-form-item>
							<el-form-item label="检查方式"  style="display:inline-block;width:48%;" :required='must'>
								<el-select v-model="formAdd.checkMode"  placeholder="请先选择检查方式" style="width: 370px;">
										<el-option
											v-for="item in dictMap.loancheck_mode"
											:key="item.id"
											:label="item.label"
											:value="item.value"/>
								</el-select>
							</el-form-item>
							<el-form-item label="任务生成规则"  style="display:inline-block;width:48%;" :required='must'>
								<el-select v-model="formAdd.rue"  placeholder="请先选择任务生成规则" style="width: 370px;">
										<el-option
											v-for="item in dictMap.loancheck_rule"
											:key="item.id"
											:label="item.label"
											:value="item.value"/>
								</el-select>
							</el-form-item>
							<el-form-item label="检查频率"  style="display:inline-block;width:48%;" :required='must'>
								<el-select v-model="formAdd.checkFrequency"  placeholder="请先选择检查频率" style="width: 370px;">
										<el-option
											v-for="item in dictMap.loancheck_frequency"
											:key="item.id"
											:label="item.label"
											:value="item.value"/>
								</el-select>
							</el-form-item>
							 <el-form-item  style="margin-bottom: 20px;display:inline-block;width:93.1%;" label="执行机构"  :required='must'>
								<treeselect   v-model="formAdd.createDept.id"  :options="depts" style="width: 100%" placeholder="选择上级类目" />
							</el-form-item>
							<el-form-item label="执行期限"  style="display:inline-block;width:48%;" :required='must'>
								<el-select v-model="formAdd.operatorPeriod"  placeholder="请先选择任务生成规则" style="width: 370px;">
										<el-option
											v-for="item in dictMap.loancheck_term"
											:key="item.id"
											:label="item.label"
											:value="item.value"/>
								</el-select>
							</el-form-item>
							 <el-form-item label="未完成措施"  style="display:inline-block;width:48%;" :required='must'>
								<el-select v-model="formAdd.measure"  placeholder="请先选择任务生成规则" style="width: 370px;">
										<el-option
											v-for="item in dictMap.loancheck_measure"
											:key="item.id"
											:label="item.label"
											:value="item.value"/>
								</el-select>
							</el-form-item>			
             </el-form>
			  <div slot="footer" class="dialog-footer">
				 <el-button type="text"  @click="cancel">取消</el-button>
				 <el-button :loading="loading" type="primary" @click="addSure">确认</el-button>
			 </div>
     </el-dialog>






  </div>
</template>

<script>
import { addRule ,delRule} from '@/api/loanManageInfo'

import checkPermission from '@/utils/permission'
import initData from '@/mixins/initData'
import initDict from '@/mixins/initDict'
import { del } from '@/api/user'
import { getDepts } from '@/api/dept'
import { parseTime } from '@/utils/index'
import eForm from './form'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  components: { eForm ,Treeselect},
  mixins: [initData, initDict],
  data() {
    return {
      height: document.documentElement.clientHeight - 180 + 'px;', isAdd: false,
	  delLoading: false, deptName: '', depts: [], deptId: null,
	  
	  trueName:null,
	  updateTrueName:null,
	  createTrueName:null,
	  
	  dept:null,

      defaultProps: {
        children: 'children',
        label: 'name'
      },
      downloadLoading: false,
      queryTypeOptions: [
        { key: 'username', display_name: '用户名' },
        { key: 'email', display_name: '邮箱' }
      ],
      enabledTypeOptions: [
        { key: 'true', display_name: '激活' },
        { key: 'false', display_name: '锁定' }
	  ],
	  ids:[],
	  id:'',
	  editData:{},
	  formm:{},
	  dialogAdd:false,

	  must:true,

	 formAdd:{
		  id:'',
		  checkType:'',
		  checkObj:'',
		  checkMode:'',
		  rue:'',
		  checkFrequency:'',
		 // createDept:null,
		  createDept:{id:'',name:''},
		  operatorPeriod:'',
		  measure:'',
		  createTime:'',
		  createUser:'',
		  updateTime:'',
		  updateUser:''

	  },

	  deleteId:'',
    }
  },
  created() {
    this.getDeptDatas()
    this.$nextTick(() => {
      this.init()
      // 加载数据字典
	 // this.getDict('user_status')
	  this.getDictMap('dept_status,loancheck_mode,loancheck_rule,loancheck_frequency,loancheck_term,loancheck_measure,loancheck_type,loancheck_obj')
	   console.log('dictMap=====',this.dictMap)
    })
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    parseTime,
    checkPermission,
    beforeInit() {
      this.url = 'api/loanManage/taskRule'
      const sort = 'id,desc'
      const query = this.query
      const type = query.type
      const value = query.value
      const enabled = query.enabled
      this.params = { page: this.page, size: this.size, sort: sort, deptId: this.deptId }
      if (type && value) { this.params[type] = value }
      if (enabled !== '' && enabled !== null) { this.params['enabled'] = enabled }
      return true
	},
	
	getDepts() {
      getDepts({ enabled: true }).then(res => {
        this.depts = res.content
      })
    },

    subDelete(id) {
      this.delLoading = true
      del(id).then(res => {
        this.delLoading = false
        this.$refs[id].doClose()
        this.dleChangePage()
        this.init()
        this.$notify({
          title: '删除成功',
          type: 'success',
          duration: 2500
        })
      }).catch(err => {
        this.delLoading = false
        this.$refs[id].doClose()
        console.log(err.response.data.message)
      })
    },
    getDeptDatas() {
      const sort = 'id,desc'
      const params = { sort: sort }
      if (this.deptName) { params['name'] = this.deptName }
      getDepts(params).then(res => {
		this.depts = res.content
		console.log('this.depts',this.depts)
      })
    },
    handleNodeClick(data) {
		console.log('data',data)
      if (data.pid === 0) {
        this.deptId = null
      } else {
        this.deptId = data.id
      }
      this.init()
	}, 
	addRule(){
        this.dialogAdd = true;
	},
	addSure(){
            const addParam = {
						operator:{id:this.formAdd.createDept.id},
						checkObj:this.formAdd.checkObj,
						checkType:this.formAdd.checkType,
						checkMode:this.formAdd.checkMode,
						rue:this.formAdd.rue,
						checkFrequency:this.formAdd.checkFrequency,
						operatorPeriod:this.formAdd.operatorPeriod.toString(),
						measure:this.formAdd.measure,
			 }
		    if(addParam.checkObj==''||addParam.checkType==''||addParam.rue == ''||addParam.checkFrequency == ''||addParam.checkMode == ''||addParam.measure == ''||addParam.operatorPeriod == ''||addParam.operator.id == ''){
				this.$message.warning('必填项未填写！')
				return;
			}
			 addRule(addParam).then(res => {
					this.resetForm()
					this.$notify({
					title: '新增成功',
					type: 'success',
					duration: 2500
					})
					this.loading = false
					this.init()
				}).catch(err => {
					this.loading = false
					console.log(err.response.data.message)
				})
 


	},

	cancel(){
       this.resetForm()
	},
	resetForm() {
      this.dialogAdd = false
      this.$refs['formAdd'].resetFields()
  
    },
    add() {
	  this.isAdd = true
	   const _this = this.$refs.form
	   _this.dialog = true
    //   this.$refs.form.getDepts()
    //   this.$refs.form.getRoles()
    //   this.$refs.form.getRoleLevel()
	 // this.$refs.form.dialog = true
	  sessionStorage.setItem('ruleDetails', JSON.stringify({}))
    },
    // 导出
    download() {
      this.downloadLoading = true
      import('@/utils/export2Excel').then(excel => {
        const tHeader = ['ID', '用户名', '邮箱', '头像地址', '状态', '注册日期', '最后修改密码日期']
		const filterVal = ['id', 'username', 'email', 'avatar', 'enabled', 'createTime', 'lastPasswordResetTime']
		console.log('this.data',this.data)
        const data = this.formatJson(filterVal, this.data)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    // 数据转换
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'createTime' || j === 'lastPasswordResetTime') {
          return parseTime(v[j])
        } else if (j === 'enabled') {
          return parseTime(v[j]) ? '启用' : '禁用'
        } else {
          return v[j]
        }
      }))
	},
	handleSelectionChange(val) {
		  console.log('val',val)
		  if(val.length>='2'){
			  this.$message.warning('请选择一个选项！')
			  return;
		  }else if(val.length == '1'){
			 this.editData =val[0]
			 console.log('this.editData',this.editData)
		  }
		//    val.forEach((v) => {
        //        this.ids.push(v.contractNo)
		//    });
		//    console.log('ids',this.ids)
		//    this.id = this.ids.toString()
		//    this.ids = []
		//    console.log('this.id',this.id)
	},
	delet(item){
		console.log('ttyyyyyy',item.id)
		delRule(item.id).then(res => {
			this.init()
			this.$notify({
			title: '删除成功',
			type: 'success',
			duration: 2500
			})
		}).catch(err => {
			console.log(err.response.data.message)
		})

	},
	editDetails(data){
		console.log('rrrr',JSON.stringify(data))
	  if(JSON.stringify(data) == "{}"){
		  this.$message.warning('请选择一个选项！')
		  return;
	  }
       this.isAdd = false
	   const _this = this.$refs.form
	   _this.getDepts()
	   console.log('data----',data)
       _this.form = {
			id: data.id,
			checkType: data.checkType,
			checkObj: data.checkObj,
			checkMode: data.checkMode,
			checkMode: data.checkMode,
			rue:data.rue,
			checkFrequency:data.checkFrequency.toString(),
			createDept:data.createDept,
			operatorPeriod:data.operatorPeriod.toString(),
			measure:data.measure,
			createDept:data.createDept,
			createTime:data.createTime,
			createUser:data.createUser,
			updateTime:data.updateTime,
			updateUser:data.updateUser,
			operator:data.operator
	  }
	  sessionStorage.setItem('ruleDetails', JSON.stringify(_this.form))
	  console.log('tttt',_this.form)
      _this.dialog = true

	},
    edit(data) {
      this.isAdd = false
      const _this = this.$refs.form
      _this.getRoles()
      _this.getDepts()
      _this.getRoleLevel()
	  _this.roleIds = []
	   console.log('createDept',data.createDept)
	   if(data.createDept){
         _this.dept = data.createDept.name;
	  }else{
		   _this.dept= null
	  }
	  console.log('_this.dept',_this.dept)
	  

	  
	  if(data.updateUser){
         _this.updateTrueName = data.updateUser.realName;
	  }else{
		  _this.updateTrueName = null
	  }
	  console.log('_this.updateTrueName',_this.updateTrueName)
	  
      if(data.createUser){
         _this.createTrueName = data.createUser.realName;
	  }else{
		  _this.createTrueName = null
	  }

      

	  _this.form = { id: data.id, username: data.username, realName:data.realName,phone: data.phone,telephone:data.telephone,remark:data.remark,createDept:_this.dept,createTime:data.createTime,createUser:_this.createTrueName,updateTime:data.updateTime,updateUser:_this.updateTrueName, email: data.email, enabled: data.enabled.toString(), roles: [], dept: { id: data.dept.id }, job: { id: data.job.id }}
	  
	  console.log('_this.form===',_this.form)
      data.roles.forEach(function(data, index) {
        _this.roleIds.push(data.id)
      })
       _this.deptId = data.dept.id
      _this.jobId = data.job.id
	  _this.getJobs(_this.deptId)
      _this.dialog = true
    }
  }
}
</script>

<style scoped>
</style>
